{% extends 'admin/dashboard.html' %}

{% block content %}
<div class="card">
    <h2 class="text-xl font-bold mb-4">留言列表</h2>
    <table class="min-w-full divide-y divide-gray-200">
        <thead class="bg-gray-50">
            <tr>
                <th scope="col" class="table-header">留言人</th>
                <th scope="col" class="table-header">邮箱</th>
                <th scope="col" class="table-header">留言内容</th>
                <th scope="col" class="table-header">操作</th>
            </tr>
        </thead>
        <tbody id="message-list" class="bg-white divide-y divide-gray-200">
            <!-- 留言数据将通过 JavaScript 动态填充 -->
        </tbody>
    </table>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取留言列表
        fetch('/admin/messages/list')
            .then(response => response.json())
            .then(data => {
                const messageList = document.getElementById('message-list');
                data.forEach(message => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td class="table-data">${message.name}</td>
                        <td class="table-data">${message.email}</td>
                        <td class="table-data">${message.content.substring(0, 50)}...</td>
                        <td class="table-data">
                            <a href="/admin/messages/detail/${message.id}" class="text-primary hover:text-primary/80">查看详情</a>
                            <a href="#" class="text-red-500 hover:text-red-700 ml-2" onclick="deleteMessage(${message.id})">删除</a>
                        </td>
                    `;
                    messageList.appendChild(row);
                });
            });
    });

    // 删除留言函数
    function deleteMessage(id) {
        if (confirm('确定要删除这条留言吗？')) {
            fetch(`/admin/messages/delete/${id}`, { method: 'DELETE' })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('删除成功');
                        // 刷新页面
                        location.reload();
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                });
        }
    }
</script>
{% endblock %}